import time
from pydantic import TypeAdapter
from sqlmodel import Session, select, func
from typing import Optional, List

from app.exception.base import AppException, HttpResp
from app.models.base import PageListOut
from app.models.system_admin import SystemAdmin, SystemAdminEditIn, SystemAdminCreateIn, SystemAdminListIn, \
    SystemAdminOut
from app.admin.service.system.role_menu import SystemRoleMenuService
from app.models.system_menu import SystemMenu
from app.utils.array import ArrayUtil


class SystemAdminService:
    def __init__(self, session: Session):
        self.session = session

    async def page_list(self, list_in: SystemAdminListIn):
        username = list_in.username
        nickname = list_in.nickname
        page_no = list_in.page_no
        page_size = list_in.page_size

        where = []
        if username:
            where.append(SystemAdmin.username.like('%{0}%'.format(username)))
        # if is_stop is not None:
        #     where.append(SystemAdmin.is_stop == is_stop)
        count_statement = (
            select(func.count())
            .select_from(SystemAdmin)
            .where(*where)
        )
        count = self.session.exec(count_statement).one()
        offset = (page_no - 1) * page_size
        statement = (
            select(SystemAdmin).where(*where).offset(offset).limit(page_size)
        )
        lists = self.session.exec(statement).all()

        return lists, count

    async def detail(self, id_: int):
        menu = self.session.get(SystemAdmin, id_)
        return menu

    async def add(self, create_in: SystemAdminCreateIn):
        """新增菜单"""
        create_dict = create_in.dict()
        create_dict['create_time'] = int(time.time())
        create_dict['update_time'] = int(time.time())
        menu_item = SystemAdmin(**create_dict)
        self.session.add(menu_item)
        self.session.commit()
        self.session.refresh(menu_item)
        return menu_item

    async def edit(self, edit_in: SystemAdminEditIn, ):
        admin_item = self.session.get(SystemAdmin, edit_in.id)
        if not admin_item:
            raise AppException(HttpResp.FAILED, msg='数据不存在!')
        # 更新菜单项的字段
        for key, value in edit_in.dict().items():
            if hasattr(admin_item, key):
                setattr(admin_item, key, value)

        # 更新 update_time 字段
        # menu_item.update_time = datetime.now()
        # 提交更改到数据库
        self.session.commit()
        self.session.refresh(admin_item)
        return admin_item

    async def delete(self, id_: int):
        menu = self.session.get(SystemAdmin, id_)
        return menu

    async def get_info(self, admin_id: int):
        system_role_menu_service = SystemRoleMenuService(self.session)
        # 管理员信息
        sys_admin = self.session.get(SystemAdmin, admin_id)
        # 角色权限
        permissions = []
        menus = []
        print('admin_id', sys_admin)
        if sys_admin:
            if sys_admin.is_super == 1:
                # 超级管理员返回所有权
                permissions.append('*')
                menus = self.session.exec(
                    select(SystemMenu).where(
                        SystemMenu.is_disable == 0,
                        SystemMenu.type.in_(['M', 'C'])
                    ).order_by(SystemMenu.sort.desc(), SystemMenu.id.desc())
                ).all()
                print('super', menus)
            else:
                # 非超级管理员返回角色权限
                role_ids = [int(i) for i in sys_admin.role_ids.split(',')]
                menu_ids = await system_role_menu_service.select_menu_ids_by_role_id(role_ids)
                if menu_ids:
                    # 查询菜单信息
                    statement = select(SystemMenu).where(
                        SystemMenu.id.in_(menu_ids),
                        SystemMenu.is_disable == 0,
                        SystemMenu.metype.in_(['M', 'C'])
                    ).order_by(SystemMenu.sort.desc(), SystemMenu.id.desc())
                    user_menus = self.session.exec(statement).all()

                    if menus:
                        menus.extend((i.perms.strip() for i in user_menus if i.perms))
                print('menus', menus)
        # if not menus:
        #     menus.append('')
        # 将 ORM 对象转换为字典形式，并排除空值字段
        menu_list = [menu.dict(exclude_none=True) for menu in menus]
        menu_tree = ArrayUtil.list_to_tree(menu_list, 'id', 'pid', 'children')
        return {
            'user': sys_admin,
            'permissions': ["*"],
            'menu': menu_tree
        }
